package com.wisnews.config.shiro;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Collection;
import java.util.Set;

/**
 * @Description：自定义redis cache缓存处理器
 * @Author: yuyd
 * @Email: yyd8358@foxmail.com
 * @Date: 2020/12/19 9:39
 * @Version 1.0
 */
@Slf4j
@Data
public class RedisCache<K,V> implements Cache<K,V> {

    private String cacheName;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public V get(K k) throws CacheException {

        log.info("<==shiro读取redis缓存信息 "+this.cacheName+" "+k);

        V v = (V)redisTemplate.opsForHash().get(this.cacheName,k.toString());

        log.info("<==shiro读取redis缓存信息成功"+this.cacheName+" "+k+":"+v);
        return v;
    }

    @Override
    public V put(K k, V v) throws CacheException {


        log.info("==>shiro信息存入redis"+this.cacheName+" "+k+":"+v);
        redisTemplate.opsForHash().put(this.cacheName,k.toString(),v);
        log.info("==>shiro信息存入redis成功");
        //打印日志
        return null;
    }

    @Override
    public V remove(K k) throws CacheException {
        log.warn("==>shiro移除redis用户缓存"+this.cacheName+" "+k);
        return (V) getRedisTemplate().opsForHash().delete(this.cacheName,k.toString());
    }

    @Override
    public void clear() throws CacheException {
        log.warn("==>shiro移除redis所有用户缓存");
            getRedisTemplate().opsForHash().delete(this.cacheName);
    }

    @Override
    public int size() {
        Long size = getRedisTemplate().opsForHash().size(this.cacheName);
        return size.intValue();
    }

    @Override
    public Set<K> keys() {
        Set keys = getRedisTemplate().opsForHash().keys(this.cacheName);
        return keys;
    }

    @Override
    public Collection<V> values() {
        return getRedisTemplate().opsForHash().values(this.cacheName);
    }

}
